package model

import (
	"time"
	"user_srv/basic/config"
)

// 灵魂匹配结果表
type XqSoulMatches struct {
	Id                 int64     `gorm:"column:id;type:bigint(20);comment:匹配ID;primaryKey;not null;" json:"id"`
	UserId1            int64     `gorm:"column:user_id_1;type:bigint(20);comment:用户1ID;not null;" json:"user_id_1"`
	UserId2            int64     `gorm:"column:user_id_2;type:bigint(20);comment:用户2ID;not null;" json:"user_id_2"`
	CompatibilityScore float64   `gorm:"column:compatibility_score;type:decimal(5,2);comment:契合度分数(0-100);not null;" json:"compatibility_score"`
	PersonalityScore   float64   `gorm:"column:personality_score;type:decimal(5,2);comment:性格契合度;" json:"personality_score"`
	LifestyleScore     float64   `gorm:"column:lifestyle_score;type:decimal(5,2);comment:生活方式契合度;" json:"lifestyle_score"`
	ValuesScore        float64   `gorm:"column:values_score;type:decimal(5,2);comment:价值观契合度;" json:"values_score"`
	RelationshipScore  float64   `gorm:"column:relationship_score;type:decimal(5,2);comment:恋爱观契合度;" json:"relationship_score"`
	CommonAnswers      string    `gorm:"column:common_answers;type:json;comment:共同答案详情;" json:"common_answers"`
	MatchReasons       string    `gorm:"column:match_reasons;type:json;comment:匹配原因分析;" json:"match_reasons"`
	CreatedAt          time.Time `gorm:"column:created_at;type:timestamp;not null;default:CURRENT_TIMESTAMP;" json:"created_at"`
	UpdatedAt          time.Time `gorm:"column:updated_at;type:timestamp;not null;default:CURRENT_TIMESTAMP;" json:"updated_at"`
}

func (x *XqSoulMatches) TableName() string {
	return "xq_soul_matches"
}

func (x *XqSoulMatches) Create() error {
	return config.DB.Create(&x).Error
}

func (x *XqSoulMatches) Delete(where XqSoulMatches) error {
	return config.DB.Where(where).Delete(&x).Error
}

func (x *XqSoulMatches) Update(where XqSoulMatches) error {
	return config.DB.Where(where).Updates(&x).Error
}

func (x *XqSoulMatches) List(where XqSoulMatches) ([]XqSoulMatches, error) {
	var matches []XqSoulMatches
	err := config.DB.Where(where).Find(&matches).Error
	return matches, err
}

func (x *XqSoulMatches) GetByUserIds(userId1, userId2 int64) (*XqSoulMatches, error) {
	var match XqSoulMatches
	err := config.DB.Where("((user_id_1 = ? AND user_id_2 = ?) OR (user_id_1 = ? AND user_id_2 = ?))",
		userId1, userId2, userId2, userId1).First(&match).Error
	return &match, err
}

func (x *XqSoulMatches) ListByUserId(userId int64, limit, offset int) ([]XqSoulMatches, error) {
	var matches []XqSoulMatches
	err := config.DB.Where("user_id_1 = ? OR user_id_2 = ?", userId, userId).
		Order("compatibility_score DESC").
		Limit(limit).Offset(offset).
		Find(&matches).Error
	return matches, err
}

func (x *XqSoulMatches) CountByUserId(userId int64) (int64, error) {
	var count int64
	err := config.DB.Model(&XqSoulMatches{}).Where("user_id_1 = ? OR user_id_2 = ?", userId, userId).Count(&count).Error
	return count, err
}
